//
//  BandCardAddViewController.m
//  网络货运PRO版
//
//  Created 网络货运PRO版 on 2019/12/24.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "GDBandCardAddViewController.h"
#import "CYCityChooseView.h"
#import "STPickerView.h"
#import "STPickerSingle.h"
#import "STPickerArea.h"
#import "TZImagePickerController.h"
#import "SelectBankListVC.h"

@interface GDBandCardAddViewController ()<STPickerAreaDelegate, STPickerSingleDelegate, CYChooseRegionDelegate, TZImagePickerControllerDelegate>
{
    NSString *_provinceStr;
    NSString *_cityStr;
    NSString *_provinceCode;
    NSString *_cityCode;
    NSString *_bankNameStr;
    NSString *_bankCode;
    NSString *_accountType;
    NSString *_accountTypeTitle;
    NSString *_kaiHuWangDianString;
    NSString *_cardTypeString;
    NSString *_cardTypeCode;
    NSString *_bindCardStatus;
    NSString *_isDefault;//是否默认
    NSString *_bankMainCode;//银行主code
}
@property (weak, nonatomic) IBOutlet UIButton *chooseBankButton;
@property (weak, nonatomic) IBOutlet UITextField *bankCardNumTextField;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UIButton *accountTypeButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (weak, nonatomic) IBOutlet UIButton *chooseCardTypeButton;

@property (nonatomic,strong) NSMutableArray *khwdArray;
@property (nonatomic,strong) NSMutableArray *khwdModelArray;
@property (nonatomic,strong) NSArray<NSDictionary *> *cardTypesMArray;
@property (nonatomic,strong) NSMutableArray *cardTypesTitleMArray;
@property (nonatomic,strong) NSDictionary *editInfoDic;

@property (nonatomic,strong) STPickerSingle *bankPickerSingle;
@property (nonatomic,strong) STPickerSingle *accountPickerSingle;
@property (nonatomic,strong) STPickerSingle *cardTypePickerSingle;
@property (nonatomic,strong) STPickerSingle *kaiHuWangDianPickerSingle;

@property (strong , nonatomic)SelectBankListModel *selectBankModel;

@end

@implementation GDBandCardAddViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _provinceStr = @"";
    _cityStr = @"";
    _provinceCode = @"";
    _cityCode = @"";
    _bankNameStr = @"";
    _bankCode = @"";
    _accountType = @"1";
    _isDefault = @"0";
    _kaiHuWangDianString = @"";
    _bankMainCode = @"";
    _cardTypeString = @"";
    _cardTypeCode = @"";
    _bindCardStatus = @"";
    
    [self baseLayout];
    if (!_isEdit) {
        [self getBankCardType:nil];
    }
}

- (void)getBankCardType:(NSString *)code {
    WEAKSELF
    NSDictionary *parmas = @{@"type": @"cardType", @"token": [UserDefaultUtil valueForKey:USER_TOKEN],};
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],@"/dict") withParameter:parmas withVC:self netName:@"银行卡类型" success:^(id response, NSString *msg) {
        
        weakSelf.cardTypesMArray = response[@"records"];
        for (NSDictionary *obj in weakSelf.cardTypesMArray) {
            [weakSelf.cardTypesTitleMArray addObject:obj[@"name"]];
            
            if (code.isNotBlank && [obj[@"code"] isEqualToString:code]) {
                [weakSelf.chooseCardTypeButton setTitle:obj[@"name"] forState:UIControlStateNormal];
            }
        }
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)baseLayout {
    
    self.navigationItem.title = _isEdit ? @"编辑银行卡" : @"新增银行卡";
    self.view.backgroundColor = BackgroundColor;
    [_saveButton setBackgroundColor:Theme_ColorValue];
    cut(_saveButton, BTN_BORDER_RADIUS);
//    [_chooseBankButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
//    [_chooseCityButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
//    [_accountTypeButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
//    [_kaiHuWangDianBtn setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    
    if (_isEdit) {
        
        [self editBankCardRequest];
        
    }
}

///获取中台银行网点、联行号
- (void)getBankAssociationNumberRequest {
    WEAKSELF
    NSDictionary *parmas = @{
        @"bankCode": _isEdit ? _editInfoDic[@"bankNo"] : _selectBankModel.code,
        @"pageNum": @"1",
        @"pageSize": @"20",
    };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/bankCard/getBankAssociationNumber", [ReAddressDynamic shared].baseUrl) withParameter:parmas withVC:self netName:@"获取中台银行网点" success:^(id response, NSString *msg) {
        
        if ([DCSpeedy isBlankArr:response[@"records"]] == NO) {
            self.khwdModelArray = response[@"records"];
            [self.khwdModelArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [weakSelf.khwdArray addObject:obj[@"bankName"]];
            }];
        }
        
        [_kaiHuWangDianPickerSingle setArrayData:self.khwdArray];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)editBankCardRequest {
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/bankCard/%@", [ReAddressDynamic shared].baseUrl, _model.code) withParameter:nil withVC:self netName:@"编辑银行卡" success:^(id response, NSString *msg) {
        
        if ([DCSpeedy isBlankDictionary:response] == NO) {
            
            _editInfoDic = response;
            
            [_chooseBankButton setTitle:response[@"bankName"] forState:UIControlStateNormal];
            _bankNameStr = response[@"bankName"];
            _bankCardNumTextField.text = response[@"account"];
            _nameTextField.text = response[@"name"];
            _kaiHuWangDianString = response[@"branche"];//开户网点
            _provinceStr = response[@"province"];
            _cityStr = response[@"city"];
            _provinceCode = response[@"provinceCode"];
            _cityCode = response[@"cityCode"];
            _accountType = CJStringWithFormat(@"%@", response[@"type"]);
            [_accountTypeButton setTitle:[response[@"type"] intValue] == 1 ? @"个人账户" : @"企业账户" forState:UIControlStateNormal];
            _isDefault = CJStringWithFormat(@"%@", response[@"isDefault"]);
            _bankCode = CJStringWithFormat(@"%@", response[@"bankAssociationNumber"]);
            _bindCardStatus = response[@"bindCardStatus"];
            _bankMainCode = response[@"bankNo"];
            _cardTypeCode = response[@"cardType"];
            [self getBankCardType:_cardTypeCode];
        }
   
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
    
}

- (IBAction)btnTypeClick:(UIButton *)sender {
    
    [self.view endEditing:YES];
    
    WEAKSELF
    if (sender.tag == 10) {
        //选择银行
        //        _bankPickerSingle = [[STPickerSingle alloc]init];
        //        _bankPickerSingle.widthPickerComponent = ScreenW;
        //        [_bankPickerSingle setArrayData:self.bankArray];
        //        [_bankPickerSingle setTitle:@"请选择银行"];
        //        [_bankPickerSingle setContentMode:STPickerContentModeBottom];
        //        [_bankPickerSingle setDelegate:self];
        //        [_bankPickerSingle show];
        
        SelectBankListVC *sblvc = [[SelectBankListVC alloc] init];
        sblvc.isChooseBank = YES;
        [self.navigationController pushViewController:sblvc animated:YES];
        sblvc.getBankInfoBlock = ^(SelectBankListModel * _Nonnull model) {
            _bankNameStr = model.name;
            _bankMainCode = model.code;
            _selectBankModel = model;
            [_chooseBankButton setTitle:model.name forState:UIControlStateNormal];
        };
        
    } else if (sender.tag == 20) {
        //选择省市
        [self.view endEditing:YES];
        //        STPickerArea *pickerArea = [[STPickerArea alloc]init];
        //        [pickerArea setDelegate:self];
        //        [pickerArea setSaveHistory:NO];
        //        [pickerArea setContentMode:STPickerContentModeBottom];
        //        [pickerArea show];
        
        [[CYCityChooseView shared] show];
        [CYCityChooseView shared].pageShowFlag = 1;
        [CYCityChooseView shared].delegate = self;
        
    } else if (sender.tag == 30) {
        //选择账户类型
        [self.view endEditing:YES];
        NSMutableArray *muArr = [[NSMutableArray alloc] initWithObjects:@"个人账户", @"企业账户", nil];
        _accountPickerSingle = [[STPickerSingle alloc] init];
        _accountPickerSingle.widthPickerComponent = ScreenW;
        [_accountPickerSingle setArrayData:muArr];
        [_accountPickerSingle setTitle:@"请选择账户类型"];
        [_accountPickerSingle setContentMode:STPickerContentModeBottom];
        [_accountPickerSingle setDelegate:self];
        [_accountPickerSingle show];
        
    } else if (sender.tag == 40) {
        // 选择银行卡类型
        [self.view endEditing:YES];
        _cardTypePickerSingle = [[STPickerSingle alloc] init];
        _cardTypePickerSingle.widthPickerComponent = ScreenW;
        [_cardTypePickerSingle setArrayData:_cardTypesTitleMArray];
        [_cardTypePickerSingle setTitle:@"请选择银行卡类型"];
        [_cardTypePickerSingle setContentMode:STPickerContentModeBottom];
        [_cardTypePickerSingle setDelegate:self];
        [_cardTypePickerSingle show];
        
    } else if (sender.tag == 50) {
        //选择开户网点
        if ([DCSpeedy isBlankString:_bankNameStr]) {
            [XSInfoView showInfo:@"请先选择开户行" onView:self.view];
            return;
        }
        
        SelectBankListVC *sblvc = [[SelectBankListVC alloc] init];
        sblvc.bankCode = _isEdit ? _editInfoDic[@"bankNo"] : _selectBankModel.code;
        if ([_cityStr isNotBlank]) {
            sblvc.bankNameS = [_cityStr stringByReplacingOccurrencesOfString:@"市" withString:@""];
        }
        [self.navigationController pushViewController:sblvc animated:YES];
        sblvc.getBankOutletInfoBlock = ^(SelectBankOutletListModel * _Nonnull model) {
            _kaiHuWangDianString = model.bankName;
//            [_kaiHuWangDianBtn setTitleColor:Dark_TextColor forState:UIControlStateNormal];
            _bankCode = model.bankNo;
        };
        
//        _kaiHuWangDianPickerSingle = [[STPickerSingle alloc]init];
//        _kaiHuWangDianPickerSingle.widthPickerComponent = ScreenW;
//        [_kaiHuWangDianPickerSingle setTitle:@"请选择开户网点"];
//        [_kaiHuWangDianPickerSingle setContentMode:STPickerContentModeBottom];
//        [_kaiHuWangDianPickerSingle setDelegate:self];
//        [_kaiHuWangDianPickerSingle show];
//
//        if ([DCSpeedy isBlankArr:self.khwdModelArray]) {
//            [self getBankAssociationNumberRequest];
//        } else {
//            [_kaiHuWangDianPickerSingle setArrayData:self.khwdArray];
//        }
        
    } else if (sender.tag == 70) {
        
        if ([DCSpeedy isBlankString:_bankNameStr]) {
            [XSInfoView showInfo:@"请选择开户银行" onView:self.view];
            return;
        }
        
//        if (![_cardTypeString isNotBlank]) {
//            [XSInfoView showInfo:@"请选择银行卡类型" onView:self.view];
//            return;
//        }
        
        if ([DCSpeedy isBlankString:_bankCardNumTextField.text]) {
            [XSInfoView showInfo:@"请输入银行卡号" onView:self.view];
            return;
        }
        
        if ([DCSpeedy isBlankString:_nameTextField.text]) {
            [XSInfoView showInfo:@"请输入开户人姓名" onView:self.view];
            return;
        }
        
        
//        if ([DCSpeedy isBlankString:_cityCode]) {
//            [XSInfoView showInfo:@"请选择开户城市" onView:self.view];
//            return;
//        }
//        
//        if ([DCSpeedy isBlankString:_kaiHuWangDianString]) {
//            [XSInfoView showInfo:@"请选择或输入开户网点" onView:self.view];
//            return;
//        }

//        if (![_accountTypeTitle isNotBlank]) {
//            [XSInfoView showInfo:@"请选择账户类型" onView:self.view];
//            return;
//        }
        

        //        移动端银行卡维护去掉开户人姓名校验（校验规则变更了，后台校验）9-25
        //        if (![[[UserDefaultUtil valueForKey:Login_Branch] valueForKey:@"name"] isEqual: _nameTextField.text]) {
        //            //银行卡时增加开户人名与认证信息人名进行判断，不一致时无法进行新增完成
        //            [XSInfoView showInfo:@"开户人名与认证信息人名不一致，请确认！" onView:self.view];
        //            return;
        //        }
        NSString *originalString = _bankCardNumTextField.text;
        NSArray *components = [originalString componentsSeparatedByString:@" "];
        NSString *noSpacesString = [components componentsJoinedByString:@""];
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        [params setValue:_bankMainCode forKey:@"bankNo"];//开户银行code
        [params setValue:_nameTextField.text forKey:@"name"];
        [params setValue:noSpacesString forKey:@"account"];//银行卡号
        [params setValue:_bankNameStr forKey:@"bankName"];//开户银行名称
//        [params setValue:_provinceStr forKey:@"province"];
//        [params setValue:_cityStr forKey:@"city"];
//        [params setValue:_provinceCode forKey:@"provinceCode"];
//        [params setValue:_cityCode forKey:@"cityCode"];
//        [params setValue:_kaiHuWangDianString forKey:@"branche"];
        [params setValue:@"1" forKey:@"type"];
        [params setValue:_isDefault forKey:@"isDefault"];
//        [params setValue:_bankCode forKey:@"bankAssociationNumber"];//开户网点code
        [params setValue:@"DC" forKey:@"cardType"];
        [params setValue:[UserDefaultUtil valueForKey:USER_TOKEN] forKey:@"token"];
        
        if (_isEdit) {
            // 修改信息
            [params setValue:_editInfoDic[@"code"] forKey:@"code"];
            [params setValue:_bindCardStatus forKey:@"bindCardStatus"];

            [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@", [NSString stringWithFormat:@"%@/ntocc-basic-api/bankCard",[ReAddressDynamic shared].baseUrl]) withParameter:params withVC:self netName:@"修改银行卡" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:msg onView:self.view];
                
                [KNotificationCenter postNotificationName:LOGIN_SUCCESS object:@"1"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } else {
            // 新增
            [params setValue:@"0" forKey:@"bindCardStatus"];
            
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], BANKCARD) withParameter:params withVC:self netName:@"新增银行卡" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:msg onView:self.view];
                
                [KNotificationCenter postNotificationName:LOGIN_SUCCESS object:@"1"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
        }
        
    } else if (sender.tag == 100) {
     
#pragma mark - OCR识别银行卡
        [SystemPermissionsToolObject determineLatestPermissionsOfTheLocalAlbum];
        
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
        imagePickerVc.allowPickingVideo = NO;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            
            [HTTPManager postUploadFiles:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD) file:photos fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
                
                [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], NTOCC_OCRCARD) withParameter:@{@"image": response[@"data"],@"ocrType": @"ocrBankCard"} withVC:self netName:@"银行卡识别" success:^(id response, NSString *msg) {
                    
                    [XSInfoView showInfo:msg onView:weakSelf.view];
                    
                    _bankCardNumTextField.text = response[@"bankCardNumber"];
                    
                    //银行卡OCR识别后不赋值开户行了，开户行让自己选择
//                    _bankNameStr = response[@"bankName"];
//                    UIButton *bankBtn = [self.view viewWithTag:10];
//                    [bankBtn setTitle:response[@"bankName"] forState:UIControlStateNormal];
                    
                } failure:^(NSInteger code, NSString *msg) {
                    
                }];
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        }];
        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

#pragma mark - CYChooseRegionDelegate
- (void)getAllInfoProvinceCode:(NSString *)provinceCode provinceName:(NSString *)provinceName cityCode:(NSString *)cityCode cityName:(NSString *)cityName countyCode:(NSString *)countyCode countyName:(NSString *)countyName {
    
    _provinceStr = provinceName;
    _provinceCode = provinceCode;
    _cityStr = cityName;
    _cityCode = cityCode;
    
    UIButton *cityBtn = [self.view viewWithTag:20];
    
//    [cityBtn setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    
    [cityBtn setTitle:CJStringWithFormat(@"%@%@",provinceName,cityName) forState:UIControlStateNormal];
}

#pragma mark -- STPickerSingleDelegate
- (void)pickerSingle:(STPickerSingle *)pickerSingle selectedTitle:(NSString *)selectedTitle
{
    if (pickerSingle == _accountPickerSingle) {
        
        UIButton *accountBtn = [self.view viewWithTag:30];
        _accountTypeTitle = selectedTitle;
        [accountBtn setTitle:selectedTitle forState:UIControlStateNormal];
        
//        [accountBtn setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        
        if ([selectedTitle isEqual:@"个人账户"]) {
            _accountType = @"1";
        } else {
            _accountType = @"2";
        }
        
    } else if (pickerSingle == _kaiHuWangDianPickerSingle){
        //开户网点
        _kaiHuWangDianString = selectedTitle;
//        [_kaiHuWangDianBtn setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        NSInteger index = [self.khwdArray indexOfObject:selectedTitle];
        _bankCode = self.khwdModelArray[index][@"bankNo"];
    } else if (pickerSingle == _cardTypePickerSingle) {
        // 银行卡类型
        _cardTypeString = selectedTitle;
        [_chooseCardTypeButton setTitle:selectedTitle forState:UIControlStateNormal];
        NSInteger index = [self.cardTypesTitleMArray indexOfObject:selectedTitle];
        _cardTypeCode = self.cardTypesMArray[index][@"code"];
    }
    
}

- (void)pickerArea:(STPickerArea *)pickerArea province:(NSString *)province city:(NSString *)city area:(NSString *)area
{
    _provinceStr = CJStringWithFormat(@"%@",province);
    
    _cityStr = CJStringWithFormat(@"%@",city);;
    
    UIButton *cityBtn = [self.view viewWithTag:20];
    
//    [cityBtn setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    
    [cityBtn setTitle:CJStringWithFormat(@"%@%@",province,city) forState:UIControlStateNormal];
}

- (NSMutableArray *)khwdArray {
    if (!_khwdArray) {
        _khwdArray = [[NSMutableArray alloc] init];
    }
    return _khwdArray;
}

- (NSMutableArray *)khwdModelArray {
    if (!_khwdModelArray) {
        _khwdModelArray = [[NSMutableArray alloc] init];
    }
    return _khwdModelArray;
}

- (NSArray<NSDictionary *> *)cardTypesMArray {
    if (!_cardTypesMArray) {
        _cardTypesMArray = [[NSMutableArray alloc] init];
    }
    return _cardTypesMArray;
}

- (NSMutableArray *)cardTypesTitleMArray {
    if (!_cardTypesTitleMArray) {
        _cardTypesTitleMArray = [[NSMutableArray alloc] init];
    }
    return _cardTypesTitleMArray;
}

@end
